<?php

/**
 * 客户端相关数据 Model
 */
class qiniuModel
{
    /**
     * 基类
     * @var object
     */
    private $base;
    public function __construct(& $base)
    {
        $this->base = $base;
    }
    /* 本地上传图片到七牛
    * string $inputname
    * string $img_name
    * retrun string $return
    */
    public function uploadQiNiuImg($inputname, $img_name='')
    {
        if(empty($_FILES[$inputname]))
        {
            return '';
        }
        require_once("static/qiniusdk/qiniu/io.php");
        require_once("static/qiniusdk/qiniu/rs.php");
        isset($this->config['qiniu']) ? extract($this->config['qiniu']):extract($this->base->config['qiniu']);
        $inputnameArr = explode('.', $_FILES[$inputname]['name']);
        $imgExtention = strtolower(end($inputnameArr));
        if ($_FILES[$inputname]['error'] == 0 && (in_array($_FILES[$inputname]['type'], array('image/png', 'image/gif', 'image/jpeg')) || in_array($imgExtention,array('jpg','jpeg','gif','png'))))
        {
            $fileName = empty($img_name)? $_FILES[$inputname]['name'] : $img_name.'.'.$imgExtention;

            Qiniu_SetKeys($accessKey, $secretKey);
            $putPolicy = new Qiniu_RS_PutPolicy("$bucket:$fileName");

            $upToken = $putPolicy->Token(null);
            $putExtra = new Qiniu_PutExtra();
            $putExtra->Crc32 = 1;
            $putExtra->MimeType = $_FILES[$inputname]['type'];

            list($result, $err) = Qiniu_PutFile($upToken, $fileName, $_FILES[$inputname]['tmp_name'], $putExtra);
            if($err == NULL)
            {
                return 'http://'.$bucket.'.'.$host.$result['key'];
            }
        }
        return false;
    }
    /* 保存网络图片到七牛
    * string $inputname
    * string $img_name
    * retrun string $return
    */
    public function saveNetImg($url, $fileName='')
    {
        $result = '';
        require_once("static/qiniusdk/qiniu/io.php");
        require_once("static/qiniusdk/qiniu/rs.php");
        extract($this->base->config['qiniu']);

        $content = common::getContents($url);
        if(empty($content))
        {
            return '';
        }
        $fix = '.jpg';
        $upPath = $this->base->config['log-dir'] . 'tmp/';
        $tmpFile = $upPath . common::getHashStr(3).$fix;

        !file_exists($upPath) && mkdir($upPath);
        $fp = fopen($tmpFile, "w");
        if (fwrite($fp, $content))
        {
            empty($fileName) && $fileName = md5(time().common::getHashStr(6)).$fix;
            Qiniu_SetKeys($accessKey, $secretKey);
            $putPolicy = new Qiniu_RS_PutPolicy("$bucket:$fileName");

            $upToken = $putPolicy->Token(null);
            $putExtra = new Qiniu_PutExtra();
            $putExtra->Crc32 = 1;

            list($data, $err) = Qiniu_PutFile($upToken, $fileName, $tmpFile, $putExtra);
            if($err == NULL)
            {
                $result = 'http://'.$bucket.'.'.$host.$data['key'];
            }
        }
        fclose($fp);
        return $result;
    }
    /**
     * @param 七牛持久化图片处理
     * @param string 七牛图片url
     * @param fops 处理图片的串行化接口
     * @param newsKey 新图片的key
     * @return string
     */
    public function qiniuPersist($url, $fops, $newKey='')
    {
        $result = false;
        if(empty($url)) return $result;
        extract($this->base->config['qiniu']);
        $key = str_ireplace('http://'.$bucket.'.'.$host, '', $url);
        empty($newKey) && $newKey = 'tb'.$key;
        //生成EncodedEntryURI的值
        $encodedEntryURI=common::urlsafe_base64_encode("$bucket:$newKey");
        $imgUrl = $bucket.'.'.$host.$key;
        $imgUrl .= $fops;
        $imgUrl .= '|saveas/'.$encodedEntryURI;

        $sign = hash_hmac("sha1", $imgUrl,$secretKey, true);
        //对签名进行URL安全的Base64编码
        $encodedSign = common::urlsafe_base64_encode($sign);

        //最终得到的完整下载URL
        $data = common::getContents("http://".$imgUrl."/sign/".$accessKey.":".$encodedSign);
        $data = json_decode($data, true);
        if(isset($data['key']))
        {
            $result = 'http://'.$bucket.'.'.$host.$data['key'];
        }
        return $result;
    }
    /**
     * @param 七年图片host
     */
    public function getQNHost()
    {
        extract($this->base->config['qiniu']);
        return 'http://'.$bucket.'.'.$host;
    }
    
    /**
     * 删除文件
     */
    public function batchDeleteImg($urls){
        require_once("static/qiniusdk/qiniu/io.php");
        require_once("static/qiniusdk/qiniu/rs.php");
        extract($this->base->config['qiniu']);
        
        $client = new Qiniu_HttpClient(null);
        $entryPaths = [];
        foreach($urls as $url){
            $key = substr($url,strlen('http://'.$bucket.'.'.$host));
            $entryPaths[] = new Qiniu_RS_EntryPath($bucket,$key);
        }
        Qiniu_RS_BatchDelete($client,$entryPaths);
    }

    /* 本地上传APP安装包到七牛
    * string $inputname
    * string $img_name
    * retrun string $return
    */
    public function uploadQiNiuApk($inputname, $img_name='')
    {
        if(empty($_FILES[$inputname]))
        {
            return false;
        }
        require_once("static/qiniusdk/qiniu/io.php");
        require_once("static/qiniusdk/qiniu/rs.php");
        isset($this->config['qiniu']) ? extract($this->config['qiniu']):extract($this->base->config['qiniu']);
        $inputnameArr = explode('.', $_FILES[$inputname]['name']);
        $imgExtention = strtolower(end($inputnameArr));
        if ($_FILES[$inputname]['error'] == UPLOAD_ERR_OK && in_array($_FILES[$inputname]['type'], array('application/octet-stream')) &&  in_array($imgExtention,array('apk', 'ipk')))
        {
            $fileName = empty($img_name)? $_FILES[$inputname]['name'] : $img_name.'.'.$imgExtention;

            Qiniu_SetKeys($accessKey, $secretKey);
            $putPolicy = new Qiniu_RS_PutPolicy("$bucket:$fileName");

            $upToken = $putPolicy->Token(null);
            $putExtra = new Qiniu_PutExtra();
            $putExtra->Crc32 = 1;
            $putExtra->MimeType = $_FILES[$inputname]['type'];

            list($result, $err) = Qiniu_PutFile($upToken, $fileName, $_FILES[$inputname]['tmp_name'], $putExtra);
            if($err == NULL)
            {
                return 'http://'.$bucket.'.'.$host.$result['key'];
            }
        }
        return false;
    }

    /* 本地上传EXCEL到七牛
    * string $inputname
    * string $img_name
    * retrun string $return
    */
    public function uploadQiNiuExcel($inputname, $excel_name='')
    {
        if(empty($_FILES[$inputname]))
        {
            return false;
        }
        require_once("static/qiniusdk/qiniu/io.php");
        require_once("static/qiniusdk/qiniu/rs.php");
        isset($this->config['qiniu']) ? extract($this->config['qiniu']):extract($this->base->config['qiniu']);
        $inputnameArr = explode('.', $_FILES[$inputname]['name']);
        $imgExtention = strtolower(end($inputnameArr));
        if ($_FILES[$inputname]['error'] == UPLOAD_ERR_OK && in_array($_FILES[$inputname]['type'], array('application/vnd.ms-excel')) &&  in_array($imgExtention,array('xlsx','xls')))
        {
            $fileName = empty($excel_name)? $_FILES[$inputname]['name'] : $excel_name.'.'.$imgExtention;

            Qiniu_SetKeys($accessKey, $secretKey);
            $putPolicy = new Qiniu_RS_PutPolicy("$bucket:$fileName");

            $upToken = $putPolicy->Token(null);
            $putExtra = new Qiniu_PutExtra();
            $putExtra->Crc32 = 1;
            $putExtra->MimeType = $_FILES[$inputname]['type'];

            list($result, $err) = Qiniu_PutFile($upToken, $fileName, $_FILES[$inputname]['tmp_name'], $putExtra);
            if($err == NULL)
            {
                return 'http://'.$bucket.'.'.$host.$result['key'];
            }
        }
        return false;
    }

    /* 本地上传热修复补丁到七牛
   * string $inputname
   * string $img_name
   * retrun string $return
   */
    public function uploadQiNiuHotRepart($inputname, $img_name='')
    {
        //$this->base->load('log')->writeLog('hotRepair','I-0:'.var_export($_FILES[$inputname],true).PHP_EOL,'repair.ext');
        if(empty($_FILES[$inputname]))
        {
            return false;
        }
        require_once("static/qiniusdk/qiniu/io.php");
        require_once("static/qiniusdk/qiniu/rs.php");
        isset($this->config['qiniu']) ? extract($this->config['qiniu']):extract($this->base->config['qiniu']);
        $inputnameArr = explode('.', $_FILES[$inputname]['name']);
        $imgExtention = strtolower(end($inputnameArr));
        //$this->base->load('log')->writeLog('hotRepair','I-2:'.var_export($imgExtention,true),'repair.ext');
        if ($_FILES[$inputname]['error'] == UPLOAD_ERR_OK  &&  in_array($imgExtention,array('js','jar')))
        {
            $fileName = empty($img_name)? $_FILES[$inputname]['name'] : $img_name.'.'.$imgExtention;
            Qiniu_SetKeys($accessKey, $secretKey);
            $putPolicy = new Qiniu_RS_PutPolicy("$bucket:$fileName");

            $upToken = $putPolicy->Token(null);
            $putExtra = new Qiniu_PutExtra();
            $putExtra->Crc32 = 1;
            $putExtra->MimeType = $_FILES[$inputname]['type'];

            list($result, $err) = Qiniu_PutFile($upToken, $fileName, $_FILES[$inputname]['tmp_name'], $putExtra);
            //$this->base->load('log')->writeLog('hotRepair','I-2:'.var_export($err,true),'repair.ext');
            if($err == NULL){
                return 'http://'.$bucket.'.'.$host.$result['key'];
            }
        }
        return false;
    }
}
